package com.erji.admin.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;

import com.erji.admin.exception.SysErrorCode;
import com.erji.common.utils.Assert;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.client.RestTemplate;

import java.util.HashMap;
import java.util.Map;

/**
 * @Description 小程序api工具类
 * @Author Lynkin
 * @Date 2023/12/17
 */
public class AppletRequestUtils {

    // 获取AccessToken
    public static JSONObject getAccessToken(String appId, String appSecret) {
        String apiUrl = StrUtil.format(
                "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={}&secret={}",
                appId, appSecret
        );
        String body = HttpRequest.get(apiUrl).execute().body();
        Assert.notNull(body, SysErrorCode.WECHAT_API_ERROR);
        return new JSONObject(body);
    }

    // 获取session_key和openid
    public static String getOpenIdByCode(String appId, String secret, String jsCode) {
        String apiUrl = StrUtil.format(
                "https://api.weixin.qq.com/sns/jscode2session?appid={}&secret={}&js_code={}&grant_type=authorization_code",
                appId, secret, jsCode
        );
        String body = HttpRequest.get(apiUrl).execute().body();
        Assert.notNull(body, SysErrorCode.WECHAT_API_ERROR);
        return body;
    }

    // 获取微信用户手机号
    public static JSONObject getPhoneNumber(String appId, String secret, String jsCode) {
        JSONObject accessToken = getAccessToken(appId, secret);


        //通过token和code来获取用户手机号
        String url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + accessToken.get("access_token");

        //封装请求体
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("code", jsCode);

        //封装请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, String>> httpEntity = new HttpEntity<>(paramMap,headers);

        //通过RestTemplate发送请求，获取到用户手机号码
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(url, httpEntity, JSONObject.class);
        //返回
        return response.getBody();
    }
}
